package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicinewarehousingEntity;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicineshelflevelService;
import city.spring.modules.medicine.service.MedicinestorehouseService;
import city.spring.modules.medicine.service.MedicinewarehousingService;
import city.spring.modules.medicine.vo.MedicinewarehousingVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：药品入库信息
 *
 * @author 谢金婷
 * @date 2020-06-24 15:09:27
 */
@RestController
@RequestMapping("/medicinewarehousing")
public class MedicinewarehousingController extends ApiController {
    private final MedicinewarehousingService medicinewarehousingService;
    private final MedicinestorehouseService storehouseService;
    private final MedicineshelflevelService shelflevelService;
    private final MedicineService medicineService;
    private final EmployeeService employeeService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicinewarehousingEntity, ?>> entityOrderFields;

    public MedicinewarehousingController(MedicinewarehousingService medicinewarehousingService, MedicinestorehouseService storehouseService, MedicineshelflevelService shelflevelService, MedicineService medicineService, EmployeeService employeeService) {
        this.medicinewarehousingService = medicinewarehousingService;
        this.storehouseService = storehouseService;
        this.shelflevelService = shelflevelService;
        this.medicineService = medicineService;
        this.employeeService = employeeService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicinewarehousingEntity::getId);
        entityOrderFields.add(MedicinewarehousingEntity::getMedicineSource);
        entityOrderFields.add(MedicinewarehousingEntity::getStorehouseId);
        entityOrderFields.add(MedicinewarehousingEntity::getWarehousingdate);
        entityOrderFields.add(MedicinewarehousingEntity::getUserId);
        entityOrderFields.add(MedicinewarehousingEntity::getGmtCreate);
        entityOrderFields.add(MedicinewarehousingEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>药品入库信息</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicinewarehousingEntity entity) {
        LambdaQueryChainWrapper<MedicinewarehousingEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品入库信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicinewarehousingVO entity, Date[] warehousingdate) {

        QueryWrapper<? extends MedicinewarehousingEntity> queryWrapper = buildQuery(entity);
        if (warehousingdate != null && warehousingdate.length == 2) {
            queryWrapper.ge("t1.warehousingdate", warehousingdate[0]);
            queryWrapper.le("t1.warehousingdate", warehousingdate[1]);
        }
        return success(medicinewarehousingService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));


//        LambdaQueryChainWrapper<MedicinewarehousingEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicinewarehousingEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicinewarehousingEntity record : page.getRecords()) {
//            try {
//                MedicinestorehouseEntity storehouseEntity = storehouseService.getById(record.getStorehouseId());
//                record.setSname(storehouseEntity.getSname());
//            } catch (Exception ignore) {
//                record.setStorehouseId(null);
//                record.setSname("< 找不到仓库 >");
//            }
//        }
//        for (MedicinewarehousingEntity record : page.getRecords()) {
//            try {
//                MedicineEntity medicineEntity = medicineService.getById(record.getMedicineId());
//                record.setMname(medicineEntity.getName());
//            } catch (Exception ignore) {
//                record.setMedicineId(null);
//                record.setMname("< 找不到药品 >");
//            }
//        }
//        for (MedicinewarehousingEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUserId());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUserId(null);
//                record.setName("< 找不到经办人 >");
//            }
//        }
//        for (MedicinewarehousingEntity record : page.getRecords()) {
//            try {
//                SupplierEntity supplierEntity = supplierService.getById(record.getSupplierId());
//                record.setSuppliername(supplierEntity.getSuppliername());
//            } catch (Exception ignore) {
//                record.setSupplierId(null);
//                record.setSuppliername("< 找不到供应商 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>药品入库信息</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
//        return success(medicinewarehousingService.getShelflevelWarehousingById(id));

        QueryWrapper<MedicinewarehousingVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicinewarehousingVO> records = medicinewarehousingService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>药品入库信息</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicinewarehousingEntity entity, @NonNull Principal user) {
        medicinewarehousingService.saveMedicinewarehousing(entity, user);

//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
        return success(entity);
    }

    /**
     * 修改一个 <strong>药品入库信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicinewarehousingEntity entity) {
        entity.setId(id);
        medicinewarehousingService.updateMedicinewarehousing(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>药品入库信息</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicinewarehousingService.deleteMedicinewarehousing(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品入库信息</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicinewarehousingService.deleteMedicinewarehousing(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicinewarehousingEntity> buildLambdaQuery(MedicinewarehousingEntity entity) {
        LambdaQueryChainWrapper<MedicinewarehousingEntity> lambdaQuery = medicinewarehousingService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MedicinewarehousingEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMedicineSource()), MedicinewarehousingEntity::getMedicineSource, entity.getMedicineSource());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStorehouseId()), MedicinewarehousingEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.eq(entity.getWarehousingdate() != null, MedicinewarehousingEntity::getWarehousingdate, entity.getWarehousingdate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUserId()), MedicinewarehousingEntity::getUserId, entity.getUserId());
        lambdaQuery.eq(entity.getGmtCreate() != null, MedicinewarehousingEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MedicinewarehousingEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinewarehousingEntity> buildQuery(MedicinewarehousingVO entity) {
        QueryWrapper<MedicinewarehousingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t2.sname", entity.getSname());
//        wrapper.eq(entity.getWarehousingdate() != null, "t1.warehousingdate", entity.getWarehousingdate());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "t1.user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t3.name", entity.getName());
        return wrapper;
    }

}
